<?php

namespace App\Http\Controllers\Admin\Auth;

use URL;
use Illuminate\Http\Request;
use App\Http\Controllers\Admin\Controller;
use App\Helper\Tree;

class RuleController extends Controller{

	protected $icon_list = [
		/* fontawesome */
		'fa fa-calendar-check-o','fa fa-clone','fa fa-commenting','fa fa-commenting-o',
		'fa fa-expeditedssl','fa fa-genderless','fa fa-get-pocket','fa fa-gg',
		'fa fa-gg-circle','fa fa-hourglass-o','fa fa-industry','fa fa-map',
		'fa fa-map-o','fa fa-map-pin','fa fa-odnoklassniki','fa fa-sticky-note',
		'fa fa-sticky-note-o','fa fa-television','fa fa-tv','fa fa-area-chart',
		'fa fa-archive','fa fa-bar-chart','fa fa-bars','fa fa-bell','fa fa-bell-o',
		'fa fa-book','fa fa-bookmark','fa fa-bullhorn','fa fa-calculator',
		'fa fa-calendar','fa fa-camera','fa fa-child','fa fa-cloud','fa fa-code',
		'fa fa-code-fork','fa fa-coffee','fa fa-cog','fa fa-cogs','fa fa-commenting',
		'fa fa-commenting-o','fa fa-comments','fa fa-comments-o','fa fa-cutlery',
		'fa fa-dashboard','fa fa-database','fa fa-desktop','fa fa-diamond',
		'fa fa-dot-circle-o','fa fa-download','fa fa-edit','fa fa-envelope',
		'fa fa-envelope-o','fa fa-file-image-o','fa fa-file-movie-o','fa fa-home',
		'fa fa-inbox','fa fa-pie-chart','fa fa-sitemap','fa fa-sun-o','fa fa-key'
	];

	/* 规则列表 */
	public function lists(Request $request){
		/* 实例化模型 */
		$adminRule  = new \App\Model\AdminRule();
		/* 树形菜单选择 */
		$list = $adminRule->get(['title','rule_as','rule_id','parent_id','is_menu','status','icon'])->toArray();
		$tree = new Tree();

		$tree->icon = array('&nbsp;&nbsp;│ ', '&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;';

        //数据处理
        foreach ($list as $key => $value) {
        	if($value['is_menu'] == 1){
        		$is_menu = '<i class="fa fa-check"></i>';
        	}else{
        		$is_menu = '<i class="fa fa-close"></i>';
        	}

        	if($value['status'] == 1){
        		$status = '<i class="fa fa-check"></i>';
        	}else{
        		$status = '<i class="fa fa-close"></i>';
        	}

        	$value['is_menu'] = '<a href="'. URL::route('admin.auth.rule.changeStatus',['option'=>'is_menu','id'=>$value['rule_id']]) .'" data-event="onstatus">'.$is_menu.'</a>';

        	$value['status'] = '<a href="'. URL::route('admin.auth.rule.changeStatus',['option'=>'status','id'=>$value['rule_id']]) .'" data-event="onstatus">'.$status.'</a>';

        	//操作菜单
        	$value['icon'] = '<i class="'.$value['icon'].'"></i>';
        	$value['manager']  = '<a href="'.URL::route('admin.auth.rule.add',['id'=>$value['rule_id']]).'" class="btn btn-white btn-bitbucket"><i class="fa fa-plus"></i> 添加下级权限</a> ';
        	$value['manager']  .= '<a href="'.URL::route('admin.auth.rule.edit',['id'=>$value['rule_id']]).'" class="btn btn-white btn-bitbucket"><i class="fa fa-paste"></i> 编辑</a> ';
        	$value['manager'] .= '<a data-text="'.$value['title'].'" data-event="ondelete" href="'.URL::route('admin.auth.rule.del',['id'=>$value['rule_id']]).'" class="btn btn-white btn-bitbucket"><i class="fa fa-exclamation-circle"></i> 删除</a> ';

        	$list[$key] = $value;
        }

		$tpl = "<tr data-event='table_tree' data-rid='\$rule_id' data-pid='\$parent_id'>";
        $tpl .= "<td>\$rule_id</td>";
        $tpl .= "<td>\$spacer \$title</td>";
        $tpl .= "<td>\$rule_as</td>";
        $tpl .= "<td>\$is_menu</td>";
        $tpl .= "<td>\$icon</td>";
        $tpl .= "<td>\$status</td>";
        $tpl .= "<td>\$manager</td>";

        /*$operation  = 'if($is_menu == 1){$extends="<td>是</td>";}else{$extends="<td>否</td>";};';
		$operation .= '$extends .= "<td>$icon</td>";';
		$operation .= 'if($status == 1){$extends.="<td>启用</td>";}else{$extends.="<td>禁用</td>";};';
		$operation .= '$extends .= "<td>菜单操作</td>";';*/

		$tree->init($list)->set_id_key('rule_id')->set_pid_key('parent_id');
		$rule_str = $tree->get_tree_html(0,$tpl);

		$data = ['rule_str'=>$rule_str];
		return view('admin.auth.rule_list',$data);
	}

	/* 添加规则 */
	public function add(Request $request){

		/* 实例化模型 */
		$adminRule  = new \App\Model\AdminRule();

		if($request->isMethod('get')){

			$id = $request->input('id');

			/* 树形菜单选择 */
			$list = $adminRule->where('status','1')->get(['title','rule_id','parent_id'])->toArray();
			
			$tree = new Tree();

			foreach ($list as $key => $r) {
                $r['selected'] = $r['rule_id'] == $id ? 'selected' : '';
                $list[$key] = $r;
            }

			$tree->init($list)->set_id_key('rule_id')->set_pid_key('parent_id');
            $tpl = "<option value='\$rule_id' \$selected>\$spacer \$title</option>";
			$menu_str = $tree->get_tree_html(0,$tpl);
			
			$data = ['icon'=>$this->icon_list , 'menu_str'=>$menu_str];
			return view('admin.auth.rule_add' , $data);
		}

		//添加权限进数据库
		$title = $request->input('title');
		$rule_as = $request->input('rule_as');
		$parent_id = (int)$request->input('parent_id');
		$icon = $request->input('icon');
		$is_menu = $request->input('is_menu');
		$is_auth = $request->input('is_auth');
		$status = $request->input('status');

		$is_menu = ($is_menu == 'on') ? 1 : 0;
		$is_auth = ($is_auth == 'on') ? 1 : 0;
		$status = ($status == 'on') ? 1 : 0;

		if(!between($title,1,16)){
			return $this->error('标题介乎1-16个字符！');
		}

		if($is_auth == 1){
			if (!between($rule_as,1,60)) {
				return $this->error('别名介乎1-60个字符！');
			}

			$insert['rule_as'] = $rule_as;
		}
		

		if(!is_id($parent_id)){
			if($parent_id != 0){
				return $this->error('上级菜单非法！');
			}
		}

		if($parent_id === 0){
			if(is_empty($icon)){
				return $this->error('iocn不能为空！');
			}

			$insert['icon'] = $icon;
		}

		$count = $adminRule->where('rule_as',$rule_as)->count();

		if($count > 0){
			return $this->error('别名已存在！');
		}

		$insert = array_merge([
			'title' => $title,
			'parent_id' => $parent_id,
			'is_menu' => $is_menu,
			'is_auth' => $is_auth,
			'status' => $status
		],$insert);

		if($adminRule->insert($insert)){
			return $this->success('添加成功！' , URL::route('admin.auth.rule.add'));
		}else{
			return $this->error('添加失败！');
		}

		
	}

	public function edit(Request $request){

		//判断ID是否合法
		$id = $request->input('id');
		if(!is_id($id)){
			return $this->error('菜单ID非法！');
		}

		$adminRule = new \App\Model\AdminRule();
		//判断ID是否存在
		if($adminRule->where('rule_id',$id)->count() < 1){
			return $this->error('菜单不存在！');
		}
		//获取数据
		$info = $adminRule->where('rule_id',$id)->first();

		if($request->isMethod('get')){

			$info->is_menu = $info->is_menu == 1 ? 'checked' : '';
			$info->is_auth = $info->is_auth == 1 ? 'checked' : '';
			$info->status  = $info->status == 1 ? 'checked' : '';

			/* 树形菜单选择 */
			$list = $adminRule->where('status','1')->get(['title','rule_id','parent_id'])->toArray();

			
			$tree = new Tree();

			foreach ($list as $key => $r) {

                $r['selected'] = ($r['rule_id'] == $info->parent_id) ? 'selected' : '';
                $list[$key] = $r;
            }

			$tree->init($list)->set_id_key('rule_id')->set_pid_key('parent_id');
            $tpl = "<option value='\$rule_id' \$selected>\$spacer \$title</option>";
			$menu_str = $tree->get_tree_html(0,$tpl);

			$data = ['info'=>$info , 'menu_str'=>$menu_str , 'icon'=>$this->icon_list];
			return view('admin.auth.rule_edit',$data);
		}

		//添加权限进数据库
		$title = $request->input('title');
		$rule_as = $request->input('rule_as');
		$parent_id = (int)$request->input('parent_id');
		$icon = $request->input('icon');
		$is_menu = $request->input('is_menu');
		$is_auth = $request->input('is_auth');
		$status = $request->input('status');

		$is_menu = ($is_menu == 'on') ? 1 : 0;
		$is_auth = ($is_auth == 'on') ? 1 : 0;
		$status = ($status == 'on') ? 1 : 0;

		if(!between($title,1,16)){
			return $this->error('标题介乎1-16个字符！');
		}

		if($is_auth == 1){
			if (!between($rule_as,1,60)) {
				return $this->error('别名介乎1-60个字符！');
			}

			$insert['rule_as'] = $rule_as;
		}

		if(!is_id($parent_id)){
			if($parent_id != 0){
				return $this->error('上级菜单非法！');
			}
		}

		if($parent_id == $id){
			return $this->error('上级菜单不能是自己！');
		}

		$insert = [];

		if($parent_id === 0){
			if(is_empty($icon)){
				return $this->error('iocn不能为空！');
			}

			$insert['icon'] = $icon;
		}

		$count = $adminRule->where('rule_as',$rule_as)->count();

		if($count > 0 && $info->rule_as != $rule_as){
			return $this->error('别名已存在！');
		}
	
		$insert = array_merge([
			'title' => $title,
			'parent_id' => $parent_id,
			'is_menu' => $is_menu,
			'is_auth' => $is_auth,
			'status' => $status
		],$insert);

		if($adminRule->where('rule_id',$id)->update($insert)){
			return $this->success('修改成功！' , URL::route('admin.auth.rule.list'));
		}else{
			return $this->error('修改失败！');
		}

	}

	public function del(Request $request){
		$id = $request->input('id');

		if(!is_id($id)){
			return $this->error('菜单ID非法！');
		}

		$adminRule = new \App\Model\AdminRule();

		$count = $adminRule->where('parent_id',$id)->count();

		if($count > 0){
			return $this->error('存在子菜单！');
		}

		if($adminRule->where('rule_id',$id)->delete()){
			return $this->success('删除成功！');
		}else{
			return $this->error('删除失败！');
		}
	}

	public function changeStatus(Request $request){
		$id = $request->input('id');
		$option = $request->input('option');

		if (!is_id($id)) {
			return $this->error('菜单ID非法！');
		}elseif (is_empty($option)) {
			return $this->error('option不能为空！');
		}

		$adminRule = new \App\Model\AdminRule();
		$status = $adminRule->changeStatus($option,$id);

		if($status === false){
			return $this->error('更新失败！');
		}else{
			return $this->success('更新成功！', null, ['status'=>$status]);
		}
	}
}